package com.hospital.payment.module.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 订单号生成工具类
 */
@Component
public class OrderNumUtils {
    @Value("${order-number-generator.prefix}")
    private String PREFIX;
    @Value("${order-number-generator.total-length}")
    private int TOTAL_LENGTH;
    private static final Random RANDOM = new Random();

    /**
     * 生成订单号
     * <br>
     * 示例：ORD20230801010101...
     */
    public String generateOrderNumber() {
        // 时间戳部分（精确到毫秒，格式：yyMMddHHmmssSSS）
        String timestamp = new SimpleDateFormat("yyMMddHHmmssSSS").format(new Date());

        // 计算剩余长度用于随机数填充
        int remainingLength = TOTAL_LENGTH - PREFIX.length() - timestamp.length();

        // 生成随机数字填充
        StringBuilder randomPart = new StringBuilder();
        for (int i = 0; i < remainingLength; i++) {
            randomPart.append(RANDOM.nextInt(10)); // 0-9之间的随机数
        }

        return PREFIX + timestamp + randomPart.toString();
    }
}
